package cn.harry.component.security.model;

import cn.harry.demo.domain.SysUser;
import cn.harry.demo.enums.StatusEnums;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义 Spring Security 用户对象
 *
 * @author harry
 * @公众号 Harry技术
 */
@Data
@NoArgsConstructor
public class SysUserDetails implements UserDetails {
    private String username;

    private SysUser sysUser;

    private Collection<SimpleGrantedAuthority> authorities;

    public SysUserDetails(SysUser user, Set<String> roles, String username) {
        this.sysUser = user;
        Set<SimpleGrantedAuthority> authorities;
        if (CollectionUtils.isNotEmpty(roles)) {
            // 标识角色 前面加上 ROLE_
            authorities = roles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).collect(Collectors.toSet());
        } else {
            authorities = Collections.emptySet();
        }

        this.authorities = authorities;
        this.username = username;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 返回当前用户的权限
        return authorities;
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    /**
     * 是否可用 ,禁用的用户不能身份验证
     *
     * @return 是否可用
     */
    @Override
    public boolean isEnabled() {
        return StatusEnums.ENABLE.getKey().equals(sysUser.getStatus());
    }
}
